<!--
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-08 08:35:19
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-08-31 01:22:18
 * @FilePath: \keep_motion_manger\src\components\importDialog\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <el-dialog :title="title" width="500px" :model-value="visible" destroy-on-close :before-close="beforeClose">
        <el-tree ref="treeRef" :node-key="'id'" :default-checked-keys="currentCheckKeys" :props="treeProps" :load="loadNode" lazy show-checkbox @check-change="handleCheckChange"/>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="beforeClose">取消</el-button>
                <el-button type="primary" @click="handleSuccess" v-if="props.type !== 'view'">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>

import { ref, reactive, defineProps, defineEmits, watch, nextTick } from 'vue';

const props = defineProps({
    id: {
        type: String,
        default: () => ''
    },
    visible: {
        type: Boolean,
        default: () => false
    },
    title: {
        type: String,
        default: () => '选择权限'
    },
    type: {
        type: String,
        default: () => 'updata'
    },
    treeProps: {
        type: Object,
        default: () => ({children: 'children', label: 'name',disabled: 'disabled'})
    },
    defaultCheckedKeys: {
        type: Array,
        default: () => []
    },
    changeFlag: {
        type: Boolean,
        default: () => false
    },
    loadNode: {
        type: Function,
        default: () => {}
    }
});

const treeRef = ref(null);
const checkedKeys = ref([]);
const emit = defineEmits(['close', 'successCallBack', 'loadNode']);
const currentCheckKeys = ref([]);

// 确定
const handleSuccess = async () => {
    emit('successCallBack', props.id, checkedKeys.value);
};

// 关闭前
const beforeClose = (done) => {
    emit('close');
};

const handleCheckChange = (data, checked, indeterminate) => {
    if(!data.isLeaf) return;
    if(checked) {
        checkedKeys.value = [...new Set([...checkedKeys.value, data.id])];
    }
    else {
        checkedKeys.value = checkedKeys.value.filter(item => item !== data.id);
    }
}
watch(() => props.changeFlag, async () => {
    await nextTick();
    treeRef.value.setCheckedKeys(checkedKeys.value);
})
watch(() => props.visible, (newVal) => {
    if(newVal) {
        checkedKeys.value = props.defaultCheckedKeys;
    }
})
</script>